package com.xiangyun.xyojbackendjudgeservice;

import cn.hutool.json.JSONUtil;
import com.xiangyun.xyojbackendcommon.common.ErrorCode;
import com.xiangyun.xyojbackendcommon.exception.BusinessException;
import com.xiangyun.xyojbackendjudgeservice.codesandbox.CodeSandBox;
import com.xiangyun.xyojbackendjudgeservice.codesandbox.CodeSandBoxFactory;
import com.xiangyun.xyojbackendjudgeservice.codesandbox.CodeSandBoxProxy;
import com.xiangyun.xyojbackendjudgeservice.codesandbox.JudgeManage;
import com.xiangyun.xyojbackendjudgeservice.strategy.JudgeContext;
import com.xiangyun.xyojbackendmodel.codesandbox.ExecuteRequest;
import com.xiangyun.xyojbackendmodel.codesandbox.ExecuteResponse;
import com.xiangyun.xyojbackendmodel.codesandbox.JudgeInfo;
import com.xiangyun.xyojbackendmodel.dto.question.JudgeCase;
import com.xiangyun.xyojbackendmodel.entity.Question;
import com.xiangyun.xyojbackendmodel.entity.QuestionSubmit;
import com.xiangyun.xyojbackendmodel.entity.User;
import com.xiangyun.xyojbackendmodel.enums.QuestionSubmitStatusEnum;
import com.xiangyun.xyojbackendserviceclient.service.QuestionFeignClient;
import com.xiangyun.xyojbackendserviceclient.service.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JudgeServiceImpl implements JudgeService {

    // 如果codesandbox.type没有值，就是example
    @Value("${codesandbox.type:example}")
    private String type;

    @Resource
    private QuestionFeignClient questionFeignClient;

    @Resource
    private UserFeignClient userFeignClient;

    @Resource
    private JudgeManage judgeManage;

    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {

        //获取提交信息和题目
        QuestionSubmit questionSubmit = questionFeignClient.getQuestionSubmitById(questionSubmitId);
        if (questionSubmit == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "提交信息不存在");
        }
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionFeignClient.getQuestionById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目信息不存在");
        }
        //如果题目提交状态不为等待中，就不用重复执行了
        if (!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())) {
            //抛出一个异常信息
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
        }

        question.setSubmitNum(question.getSubmitNum() + 1);
        questionFeignClient.updateQuestionById(question);

        //更改判题（题目提交）的状态为 "判题中"，防止重复执行，也能让用户即时看到状态
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        //及时更新题目的状态
        boolean update = questionFeignClient.updateQuestionSubmitById(questionSubmitUpdate);
        if (!update) {
            //抛出异常信息
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
        }


        //调用沙箱，获取到执行结果
        //使用了静态工厂来实现切换
        CodeSandBox codeSandBox = CodeSandBoxFactory.newInstance(type);
        //通过代理来实现增强，前后输出对应的信息
        codeSandBox = new CodeSandBoxProxy(codeSandBox);
        //设置请求需要的值
        String judgeCaseStr = question.getJudgeCase();
        //设置输入用例
        //先要获取题目的用例，然后得到对应的JSON数组，然后将输入的改为
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        String code = questionSubmit.getCode();
        String language = questionSubmit.getLanguage();
        //把请求需要的条件都丢到里面去
        ExecuteRequest executeRequest = ExecuteRequest.builder()
                .inputList(inputList)
                .code(code)
                .language(language)
                .build();

        //这一步就是在调用代码沙箱的结果
        ExecuteResponse executeResponse = codeSandBox.executeCode(executeRequest);

        List<String> outputList = executeResponse.getOutputList();
        //根据沙箱的执行结果，设置题目的判题状态和信息

        //获取判题结果信息
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executeResponse.getJudgeInfo());
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(outputList);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestion(question);
        judgeContext.setQuestionSubmit(questionSubmit);

        //我们定义了一个JudgeManage来管理这个策略，当语言在不一致的情况下面

        JudgeInfo judgeInfo = judgeManage.doJudge(judgeContext);
        judgeInfo.setPassedCount(executeResponse.getPassedCount());
        judgeInfo.setTotalCount(executeResponse.getTotalCount());
        //后面需要修改数据库中的判题结果
        questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        update = questionFeignClient.updateQuestionSubmitById(questionSubmitUpdate);
        if (!update) {
            //抛出异常信息
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
        }
        Long userId = question.getUserId();
        User user = userFeignClient.getById(userId);
        // 通过数 + 1
        if(judgeInfo.getMessage().equals("Accepted")){
            question.setAcceptedNum(question.getAcceptedNum() + 1);
            user.setAcCount(user.getAcCount() + 1);
        }
        user.setSubmitCount(user.getSubmitCount() + 1);
        userFeignClient.updateById(user);
        questionFeignClient.updateQuestionById(question);
        QuestionSubmit questionSubmitResult = questionFeignClient.getQuestionSubmitById(questionId);
        return questionSubmitResult;
    }
}
